package com.aaa.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.aaa.annotation.ForwardAnnotation;
import com.aaa.annotation.RequestMapping;
import com.alibaba.fastjson.JSON;

public class BaseServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	protected  HttpSession session =  null;
	
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//1 设置session 为全局的
		session = req.getSession();
		//2 统一编码方式为 utf-8
		req.setCharacterEncoding("UTF-8");
		//3 获取映射的最后一位
		String m = req.getRequestURI().split("/")[3];
		//4 封装请求参数到map
		Map<String, String[]> parameterMap = req.getParameterMap();//获取所有的请求参数
        Set<String> set = parameterMap.keySet(); //获取请求参数中所有key的集合
        
        Map<String,Object> map = new HashMap<>(); // 我们自己创建了一个map
        for (String s : set) { 
			map.put(  s  , parameterMap.get( s  )[0]) ;
		}
		// 5 通过反射获取 注解配置信息  调用匹配的函数
		try {
			Method[] methods = this.getClass().getDeclaredMethods();
			
			for (Method method : methods) {
				RequestMapping r = method.getAnnotation(RequestMapping.class);
				if(r != null) {
					String url = r.url();
					if( m.equals(url) ) {
						
						Object object = method.invoke(this, map);
						
						ForwardAnnotation f = method.getAnnotation(ForwardAnnotation.class);
						
						if(f == null) { //没有这个注解 代表应该返回ajax请求方式
							resp.setContentType("text/json;charset=UTF-8");
							PrintWriter out = resp.getWriter();
							String jsonString = JSON.toJSONString(object);
							out.write(jsonString);
							out.close();
						}else {
							req.getRequestDispatcher( (String)object   ).forward(req, resp);
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
/**

*/